<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>远程控制</title>
    <style>
        .control-panel {
            max-width: 800px;
            margin: 20px auto;
            padding: 20px;
            border: 1px solid #ddd;
            display: grid;
            grid-template-columns: repeat(2, 1fr);
            gap: 15px;
        }
        .sensor-btn {
            padding: 20px;
            border: none;
            border-radius: 8px;
            cursor: pointer;
            transition: 0.3s;
        }
        .sensor-btn.off {
            background: #f44336;
            color: white;
        }
        .sensor-btn.on {
            background: #4CAF50;
            color: white;
        }
        .color-btn {
            padding: 20px;
            border: none;
            border-radius: 8px;
            cursor: pointer;
            background: #2196F3;
            color: white;
        }
        .status-box {
            grid-column: 1 / -1;
            padding: 15px;
            background: #f5f5f5;
            border-radius: 8px;
            min-height: 40px;
        }
        .color-picker {
            display: none;
            position: fixed;
            top: 50%;
            left: 50%;
            transform: translate(-50%, -50%);
            background: white;
            padding: 20px;
            border: 1px solid #ddd;
            border-radius: 8px;
            box-shadow: 0 0 10px rgba(0,0,0,0.2);
            z-index: 1000;
        }
        .color-picker input {
            margin: 10px 0;
        }
        .overlay {
            display: none;
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background: rgba(0,0,0,0.5);
            z-index: 999;
        }
        .device-select {
            grid-column: 1 / -1;
            margin-bottom: 10px;
        }
    </style>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
</head>
<body>
    <div class="overlay" id="overlay" onclick="closeColorPicker()"></div>
    <div class="color-picker" id="colorPicker">
        <h3>选择 RGB 颜色</h3>
        <input type="color" id="colorInput" value="#ffffff">
        <br>
        <button onclick="submitColor()">确认</button>
        <button onclick="closeColorPicker()">取消</button>
    </div>

    <div class="control-panel">
        <h2 style="grid-column:1/-1">设备远程控制</h2>
        <div class="device-select">
            <label for="device_select">选择设备：</label>
            <select id="device_select">
                <option value="">-- 请选择设备 --</option>
            </select>
        </div>

        <button class="sensor-btn off"
                data-device="gather"
                onclick="toggleSensor(this)">
            土壤传感器：关闭
        </button>

        <button class="sensor-btn off"
                data-device="open_fan"
                onclick="toggleSensor(this)">
            风扇：关闭
        </button>

        <button class="sensor-btn off"
                data-device="open_water"
                onclick="toggleSensor(this)">
            水泵：关闭
        </button>

        <button class="sensor-btn off"
                data-device="open_led"
                onclick="toggleSensor(this)">
            LED灯：关闭
        </button>

        <button class="color-btn"
                onclick="openColorPicker()">
            设置RGB颜色
        </button>

        <div class="status-box" id="status"></div>
    </div>

    <script>
        let selectedDeviceId = '';

        // 加载设备列表
        function loadDevices() {
            $.ajax({
                url: '/api/device/list',
                success: function(data) {
                    const select = $('#device_select');
                    select.empty();
                    select.append('<option value="">-- 请选择设备 --</option>');
                    data.devices.forEach(device => {
                        select.append(`<option value="${device.id}">${device.id}</option>`);
                    });
                    if (selectedDeviceId) {
                        select.val(selectedDeviceId);
                    }
                    updateButtonStates();
                },
                error: function(xhr, status, error) {
                    console.error('加载设备列表失败:', status, error);
                    alert('无法加载设备列表');
                }
            });
        }

        // 更新按钮状态
        function updateButtonStates() {
            const deviceId = $('#device_select').val();
            if (!deviceId) return;
            $.ajax({
                url: '/api/device/info',
                data: { device_id: deviceId },
                success: function(data) {
                    document.querySelector('[data-device="gather"]').classList.toggle('true', data.soil > 0);
                    document.querySelector('[data-device="gather"]').classList.toggle('false', data.soil <= 0);
                    document.querySelector('[data-device="gather"]').textContent = `土壤传感器：${data.soil > 0 ? '开启' : '关闭'}`;
                    document.querySelector('[data-device="open_fan"]').classList.toggle('true', data.fan);
                    document.querySelector('[data-device="open_fan"]').classList.toggle('false', !data.fan);
                    document.querySelector('[data-device="open_fan"]').textContent = `风扇：${data.fan ? '开启' : '关闭'}`;
                    document.querySelector('[data-device="open_water"]').classList.toggle('true', data.water);
                    document.querySelector('[data-device="open_water"]').classList.toggle('false', !data.water);
                    document.querySelector('[data-device="open_water"]').textContent = `水泵：${data.water ? '开启' : '关闭'}`;
                    document.querySelector('[data-device="open_led"]').classList.toggle('true', data.led);
                    document.querySelector('[data-device="open_led"]').classList.toggle('false', !data.led);
                    document.querySelector('[data-device="open_led"]').textContent = `LED灯：${data.led ? '开启' : '关闭'}`;
                },
                error: function(xhr, status, error) {
                    console.error('获取设备状态失败:', status, error);
                }
            });
        }

        async function toggleSensor(btn) {
            const deviceId = $('#device_select').val();
            if (!deviceId) {
                alert('请先选择设备');
                return;
            }
            const device = btn.dataset.device;
            const isActive = btn.classList.contains('on');
            btn.classList.toggle('true');
            btn.classList.toggle('false');
            btn.textContent = `${btn.textContent.split('：')[0]}：${isActive ? '关闭' : '开启'}`;

            const state = {
                id: deviceId,
                [device]: !isActive ? 'true' : 'false'
            };

            try {
                const response = await fetch('/api/remote_control', {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/json' },
                    body: JSON.stringify(state)
                });

                const result = await response.json();
                if (response.ok) {
                    document.getElementById('status').textContent =
                        `${new Date().toLocaleTimeString()} ${device} 状态：${state[device]}`;
                } else {
                    throw new Error(result.message || '请求失败');
                }
            } catch (error) {
                console.error('控制指令发送失败:', error);
                document.getElementById('status').textContent =
                    `${device} 控制指令发送失败：${error.message}`;
                // 恢复按钮状态
                btn.classList.toggle('true');
                btn.classList.toggle('false');
                btn.textContent = `${btn.textContent.split('：')[0]}：${isActive ? '开启' : '关闭'}`;
            }
        }

        function openColorPicker() {
            const deviceId = $('#device_select').val();
            if (!deviceId) {
                alert('请先选择设备');
                return;
            }
            document.getElementById('colorPicker').style.display = 'block';
            document.getElementById('overlay').style.display = 'block';
        }

        async function submitColor() {
            const deviceId = $('#device_select').val();
            if (!deviceId) {
                alert('请先选择设备');
                return;
            }
            const color = document.getElementById('colorInput').value;
            const r = parseInt(color.slice(1, 3), 16);
            const g = parseInt(color.slice(3, 5), 16);
            const b = parseInt(color.slice(5, 7), 16);

            const state = {
                id: deviceId,
                led_red: r,
                led_green: g,
                led_blue: b
            };

            try {
                const response = await fetch('/api/remote_control', {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/json' },
                    body: JSON.stringify(state)
                });

                const result = await response.json();
                if (response.ok) {
                    document.getElementById('status').textContent =
                        `${new Date().toLocaleTimeString()} RGB颜色设置为: R${r}, G${g}, B${b}`;
                } else {
                    throw new Error(result.message || '请求失败');
                }
            } catch (error) {
                console.error('RGB颜色设置失败:', error);
                document.getElementById('status').textContent =
                    `RGB颜色设置失败：${error.message}`;
            }

            closeColorPicker();
        }

        function closeColorPicker() {
            document.getElementById('colorPicker').style.display = 'none';
            document.getElementById('overlay').style.display = 'none';
        }

        // 页面加载时初始化
        $(document).ready(function() {
            loadDevices();
            $('#device_select').on('change', function() {
                selectedDeviceId = $(this).val();
                updateButtonStates();
            });
        });
    </script>
</body>
</html>